﻿using B.WMS.IWMSService.Warehousety;
using B.WMS.StandardReturn;
using B.WMS.WMSDtos.Warehousety;
using B.WMS.WMSEntities.Warehousety;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using MiniExcelLibs;

namespace B.WMS.WMSService.Warehousety
{
    public class WarehouseService : ApplicationService, IWarehouseService
    {
        private readonly IRepository<Warehouse, Guid> _WarehouseRepository;

        public WarehouseService(IRepository<Warehouse, Guid> warehouseRepository)
        {
            _WarehouseRepository = warehouseRepository;
        }

        public async Task<ApiResult<WarehouseDto>> AddWare(CreateUpdateWarehouseDto input)
        {
            var warehouse = ObjectMapper.Map<CreateUpdateWarehouseDto,Warehouse>(input);
            warehouse.WarehouseNo= AutoCode.AutoCode.GetCode("CK").Result.ResultData;
            await _WarehouseRepository.InsertAsync(warehouse);
            return new ApiResult<WarehouseDto>() { Code = ApiCode.Success, ResultData = ObjectMapper.Map<Warehouse, WarehouseDto>(warehouse) };

        }

        public async Task<ApiResult<Warehouse>> DeleteWare(string id)
        {
            var warehouse = await _WarehouseRepository.GetAsync(x=>x.WarehouseNo==id);
            await _WarehouseRepository.DeleteAsync(warehouse);
            return new ApiResult<Warehouse>() { Code = ApiCode.Success, ResultData = warehouse };
        }

        public async Task<List<WarehouseDto>> GetWare()
        {
            var warehouses = await _WarehouseRepository.GetListAsync();
            var res = ObjectMapper.Map<List<Warehouse>,List<WarehouseDto>>( warehouses);
            return res;
        }

        public async Task<WarehouseDto> UpdateWare(CreateUpdateWarehouseDto input)
        {
            var warehouse = ObjectMapper.Map<CreateUpdateWarehouseDto, Warehouse>(input);
            await _WarehouseRepository.UpdateAsync(warehouse);
            return ObjectMapper.Map<Warehouse, WarehouseDto>(warehouse);
        }

        public async Task<ApiPaging<WarehouseDto>> GetWarePage(PageInput input)
        {
            var query = await _WarehouseRepository.GetQueryableAsync();
            var totalData = query.Count();
            var pageDatas = query.Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();
            var pageDtos = ObjectMapper.Map<List<Warehouse>, List<WarehouseDto>>(pageDatas);
            var totalPage = (int)Math.Ceiling((double)totalData / input.PageSize);
            return new ApiPaging<WarehouseDto>
            {
                Code = ApiCode.Success,
                TotalData = totalData,
                TotalPage = totalPage,
                PageDatas = pageDtos
            };
        }
        
    }
}
